<?php

App::uses('AppController', 'Controller');

/**
 * Description of OrganisationController
 *
 * @author ice
 */
class OrganisationController extends AppController {

    public $uses = array('Organisation', 'SubscriptionType', 'Member');
    public $layout = "admin";
    public $components = array('Api');
    public $helpers = array('Time', 'Timezone', 'CustomPagination', 'Dropdown', 'Cache', 'Account');
    
    public $cacheAction = array(
        'birthdays' => '1 day',
        'index' => '1 hour',
        'member_details' => '1 day'
    );

    public function beforeFilter() {
        parent::beforeFilter();

        // actions that don't need authentication
        $actions = array('index', 'login', 'logout', 'unlock', 'lock', 'forgot_password', 'account_activate', 
            'register', 'register_success', 'change_password', 'manage', 'remove');

        // check if user is not authenticated and request login
        if ( strpos($this->params['action'], 'create') !== 0 && !in_array($this->action, $actions)) {
            $this->validateOrganisationAccount();
        }
    }

    public function web_index() {
        $this->layout = "web";
    }

    public function create_select_subscription($subscription_type = null) {
        $this->layout = "members";
        
        $this->set('title_for_layout', 'Organisation Creation: Select Subscription');

        if ($subscription_type != null) {
            $subscription_type = $this->SubscriptionType->find('first', array(
                'conditions' => array('name' => $subscription_type),
                'recursive' => -1)
            );

            $signup_info = array(
                'SubscriptionType' => $subscription_type['SubscriptionType']
            );

            $this->Session->write('signup_info', $signup_info);

            $this->redirect(array('action' => 'create_profile'));
        }
    }

    public function create_profile() {
        $this->layout = "members";
        
        $this->set('title_for_layout', 'Organisation Creation: Basic Information');

        if (!$this->Session->check('signup_info')) {
            $this->redirect(array('action' => 'create_select_subscription'));
        }

        if (isset($_POST['data']['Organisation'])) {

            $signup_info = $this->Session->read('signup_info');
            $member_account = $this->Session->read('member_account');

            $sub_start_dt = new DateTime();
            $sub_end_dt = new DateTime();
            $sub_end_dt->add(new DateInterval("P1M1D"));

            $organisation = $_POST['data'];

            $organisation['Organisation']['active'] = 1;
            $organisation['OrganisationType']['id'] = $organisation['Organisation']['organisation_type_id'];
            $organisation['OrganisationType']['name'] = $this->Organisation->OrganisationType->getTypeName($organisation['Organisation']['organisation_type_id']);
            $organisation['OrganisationSubscription'][0]['subscription_start_dt'] = $sub_start_dt->format('Y-m-d H:i:s');
            $organisation['OrganisationSubscription'][0]['subscription_end_dt'] = $sub_end_dt->format('Y-m-d H:i:s');
            $organisation['OrganisationSubscription'][0]['last_renewal'] = date('Y-m-d H:i:s');
            $organisation['OrganisationAccount'] = array(
                array(
                    'member_account_id' => $member_account['MemberAccount']['id'],
                    'account_role_id' => 1
                )
            );

            /*$organisation['OrganisationAccount'][0]['raw_password'] = $organisation['OrganisationAccount'][0]['password'];
            $organisation['OrganisationAccount'][0]['password'] = md5($organisation['OrganisationAccount'][0]['password'] . $organisation['OrganisationAccount'][0]['pass_salt']);*/
            
            $signup_info['Organisation'] = $organisation;

            /*$member = array('Member' => array(), 'MemberAccount' => array());
            
            $member['Member']['first_name'] = $organisation['OrganisationAccount'][0]['first_name'];
            $member['Member']['last_name'] = $organisation['OrganisationAccount'][0]['last_name'];
            $member['Member']['email'] = $organisation['OrganisationAccount'][0]['username'];
            $member['Member']['dob'] = $organisation['Member']['dob'];
            $member['Member']['gender'] = $organisation['Member']['gender'];

            $member['MemberAccount']['username'] = $organisation['OrganisationAccount'][0]['username'];
            $member['MemberAccount']['password'] = md5($organisation['OrganisationAccount'][0]['password'] . $organisation['OrganisationAccount'][0]['pass_salt']);
            $member['MemberAccount']['pass_salt'] = $organisation['OrganisationAccount'][0]['pass_salt'];

            $this->Session->write('member_info', $member);*/

            $this->Session->write('signup_info', $signup_info);

            // skip requiring payment for a subscription that does not require billing
            if ($signup_info['SubscriptionType']['billing_required'] == "no") {
                $this->redirect(array('action' => 'create_review'));
            } else {
                $this->redirect(array('action' => 'create_payments'));
            }
        }
    }

    public function create_payments() {
        $this->layout = 'members';
        
        $this->set('title_for_layout', 'Organisation Creation: Payment Information');

        if (!$this->Session->check('signup_info')) {
            $this->redirect(array('action' => 'create_select_subscription'));
        }

        if (isset($_POST['data']['Billing'])) {

            $signup_info = $this->Session->read('signup_info');

            $signup_info['Billing'] = $_POST['data']['Billing'];

            $this->Session->write('signup_info', $signup_info);

            $this->redirect(array('action' => 'create_review'));
        }
    }

    public function create_review() {
        $this->layout = 'members';

        if (!$this->Session->check('signup_info')) {
            $this->redirect(array('action' => 'create_select_subscription'));
        }

        $this->set('signup_info', $this->Session->read('signup_info'));
        $this->set('title_for_layout', 'Organisation Creation: Review');
    }

    public function create() {
        $this->layout = "members";

        if (isset($_POST['data'])) {
            $this->autoRender = false;

            $signup_info = $this->Session->read('signup_info');
            //$member_info = $this->Session->read('member_info');
            $member_account = $this->Session->read('member_account');
            
            $organisation = $signup_info['Organisation'];
            
            $response = $this->Api->post('/organisation/create', array(
                'org_name' => $organisation['Organisation']['name'],
                'org_type_id' => $organisation['Organisation']['organisation_type_id'],
                'org_email' => $organisation['Organisation']['email'],
                'org_address' => $organisation['Organisation']['address'],
                'org_website' => $organisation['Organisation']['website'],
                'org_phone' => $organisation['Organisation']['phone'],
                'org_city' => $organisation['Organisation']['city'],
                'org_state' => $organisation['Organisation']['state'],
                'org_country' => $organisation['Organisation']['country'],
                'org_post_code' => $organisation['Organisation']['post_code'],
                'org_subscription_type_id' => $signup_info['SubscriptionType']['id'],
                'member_account_id' => $member_account['MemberAccount']['id']
                /*'account_fname' => $member_info['Member']['first_name'],
                'account_lname' => $member_info['Member']['last_name'],
                'account_dob' => $member_info['Member']['dob'],
                'account_gender' => $member_info['Member']['gender'],
                'account_username' => $organisation['OrganisationAccount'][0]['username'],
                'account_password' => $organisation['OrganisationAccount'][0]['raw_password']*/
            ));

            if ( $response['status'] == 'success' ) {

                $this->Session->delete('signup_info');
                
                // clear organisation slugs cache so it gets refreshed on next load
                Cache::delete('organisation_slugs');

                $this->redirect(array('action' => 'create_success'));
                
            } else {
                if( isset($response['message']) ) {
                    $this->Session->setFlash($response['message']);
                }
                else {
                    $this->Session->setFlash("Registration Failed Due To Server Side Error. Please Try Again.");
                }
            }

            $this->redirect(array('action' => 'create_review'));
            
        } else {
            // TODO: Return code to option to choose pricing package
            // $this->redirect(array('action' => 'create_select_subscription'));
            $this->redirect(array('action' => 'create_select_subscription', 'free trial'));
        }
    }

    public function create_success() {
        $this->layout = "members";
        
        $this->set('title_for_layout', 'Organisation Registration Complete');
    }

    public function create_cancel() {
        $this->autoRender = false;

        $this->Session->delete("signup_info");

        $this->redirect(array('controller' => 'member', 'action' => 'organisations'));
    }

    public function create_terms() {
        $this->layout = 'web';
        
        $this->set('title_for_layout', 'Organisation Creation: Terms & Conditions');
    }

    public function index() {
        $this->layout = "admin";

        $orgAccount = $this->Session->read('org_account');
        
        if( $orgAccount ) {
            
            // validate account and retrieve settings
            $this->loadOrgSettings();
            
            $response = $this->Api->post('/batch', array(
                'organisation' => array(
                    'method' => 'post',
                    'url' => '/organisation',
                    'params' => array('organisation_id' => $orgAccount['Organisation']['id'])
                ),
                'stats' => array(
                    'method' => 'post',
                    'url' => '/organisation/stats',
                    'params' => array('organisation_id' => $orgAccount['Organisation']['id'])
                ),
                'feed' => array(
                    'method' => 'post',
                    'url' => '/organisation/activityFeed',
                    'params' => array('organisation_id' => $orgAccount['Organisation']['id'])
                ),
                'general_stats' => array(
                    'method' => 'post',
                    'url' => '/organisation/general_stats',
                    'params' => array('organisation_id' => $orgAccount['Organisation']['id'])
                )
            ));
            
            // extract data into variables
            extract($response);

            $tasks = array();

            $tasks['accounts_created'] = ClassRegistry::init('OrganisationAccount')->find('count', array(
                'conditions' => array(
                    'OrganisationAccount.organisation_id' => $orgAccount['Organisation']['id']
                )
            ));

            $tasks['profile_updated'] = ClassRegistry::init('Organisation')->find('count', array(
                'conditions' => array(
                    'Organisation.id' => $orgAccount['Organisation']['id'],
                    'not' => array(
                        'Organisation.email' => null,
                        'Organisation.phone' => null
                    )
                ),
                'recursive' => -1
            ));

            $this->set(compact('orgAccount', 'organisation', 'stats', 'feed', 'general_stats', 'tasks'));
        }
        
        else {
            // use the public view action to complete the process
            $this->public_view();
        }
    }
    
    public function public_view() {
        $this->cacheAction = '1 day';
        
        $org_account = $this->Session->read('org_account');
        
        // if we are logged into an organisation and want to view it's public view
        if( $org_account ) {
            $this->layout = 'admin';
            $this->loadOrgSettings();
            $this->set('manage_option', false);
        }
        
        // we are logged in as a member and viewing and organisation's public profile
        else if( isset($this->params['organisationSlug']) && $this->Session->check('member_account') ) {
            $this->layout = 'members_no_profile';
            
            $manage_option = false;
            $member_account = $this->Session->read('member_account');
            
            foreach($member_account['OrganisationAccount'] as $org_acc){
                if( $org_acc['Organisation']['slug'] == $this->params['organisationSlug'] ) {
                    $manage_option = true;
                    break;
                }
            }
            
            $this->set('manage_option', $manage_option);
        }
        
        // we aren't logged in and viewing the organisation's public profile
        else {
            $this->layout = 'web';
            $this->set('manage_option', false);
        }
        
        $organisation = $this->Api->post('/organisation', array(
            'organisation_id' => $this->params['organisationSlug']
        ));
        
        if( $organisation ) {
        
            $members = $this->Api->post('/organisation/find_member', array(
                'organisation_id' => $organisation['Organisation']['id'],
                'organisation_member_category_id' => -1,
                'limit' => 15,
                //'sort_order' => 'recent'
            ));
            
            $this->set(compact('organisation', 'members'));

            $this->render('/Member/org_profile');
        }
        
        else {
            $this->Session->setFlash('Organisation you tried to visit does not exist. Please check and try again.');
            return $this->redirect('/');
        }
        
    }
    
    public function manage($org_slug, $check_hash) {
        $this->autoRender = false;
        
        if( !$this->Session->check('org_manage_check_hash') || $this->Session->read('org_manage_check_hash') != $check_hash ) {
            $this->Session->setFlash('Organisation account validation not performed');
            $this->redirect("/member/organisations");
        }
        
        $member_account = $this->Session->read('member_account');
        
        if( $org_slug == null && isset($this->params['organisationSlug']) ) {
            $org_slug = $this->params['organisationSlug'];
        }
        
        $result = $this->Api->post('/organisation/manage', array(
            'organisation_id' => $org_slug,
            'member_account_id' => $member_account['MemberAccount']['id']
        ));

        if ($result['status'] == 'success') {
            $this->Session->write('org_account', $result['account']);
            $this->Session->delete('org_manage_check_hash');
            
            $this->redirect("/" . $result['account']['Organisation']['slug']);
        } 
        
        else {
            $this->Session->setFlash( $result['message'] );
            $this->redirect("/member/organisations");
        }
    }

    public function login() {
        $this->layout = 'login';

        if (isset($_POST['username'])) {
            $result = $this->Api->post('/organisation/login', array(
                'username' => $_POST['username'],
                'password' => $_POST['password']
            ));

            if ($result['status'] == 'success') {
                $this->Session->write('org_account', $result['account']);
                $this->redirect("/" . $result['account']['Organisation']['slug']);
                //$this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash( $result['message'] );
            }
        }
    }

    public function logout() {
        //$this->Session->destroy();
        $this->Session->delete('org_account');
        
        $this->redirect(array('controller' => 'member', 'action' => 'organisations'));
    }

    public function lock() {
        $this->layout = 'ajax';

        // get current logged in account
        $orgAccount = $this->Session->read('org_account');
        
        if( !$orgAccount ) {
            return json_encode(array('status' => 'no_session'));
        }
        
        else {
            $this->set(compact('orgAccount'));
        }

        // destroy session so if page is refreshed we are bounced to the login screen
        $this->Session->delete('org_account');
    }
    
    public function unlock() {
        $this->autoRender = false;
        
        $member_account = $this->Session->read('member_account');
        
        if( !$member_account ) {
            return json_encode(array('status' => 'failed', 'message' => 'Session Expired', 'session_expired' => true));
        }

        if ( $this->request->is('ajax') && $this->request->is('post') ) {
            $data = $this->request->data;
            
            $response = $this->Api->post('/members/validate_login', array(
                'username' => $data['username'],
                'password' => $data['password']
            ));
            
            if( $response['status'] == 'success' && $response['valid'] ) {
                $result = $this->Api->post('/organisation/manage', array(
                    'organisation_id' => $data['org_slug'],
                    'member_account_id' => $member_account['MemberAccount']['id']
                ));

                if ($result['status'] == 'success') {
                    $this->Session->write('org_account', $result['account']);
                    $this->Session->delete('org_manage_check_hash');

                    $this->Session->write('org_account', $result['account']);

                    return json_encode(array('status' => 'success', 'message' => 'Session Unlocked'));
                } 

                else {
                    if( isset($result['message']) ) {
                        $this->Session->setFlash( $result['message'] );
                    }
                    
                    return json_encode($result);
                }
            }
            
            else {
                return json_encode($response);
            }
        }
    }

    public function forgot_password() {
        $this->layout = 'web';
        
        if( isset($_POST['Member']['email']) ) {
            $email = $_POST['Member']['email'];
            
            $response = $this->Api->post('/organisation/account/reset_password', array(
                'organisation_id' => -1, // fake the organisation_id since it is not really needed for this operation
                'username' => $email,
                'reset_url' => Router::url('/organisation/change_password', true)
            ));
            
            if( $response['status'] == 'failed' ) {
                $this->Session->setFlash($response['message']);
                $this->set('username', $email);
            }
            else {
                $this->Session->setFlash('A password reset confirmation email has been sent to specified account email. Please check in order to continue.');
                return $this->redirect("/organisation/login");
            }
            
        }
    }

    public function edit() {
        $this->layout = 'admin';

        $orgAccount = $this->Session->read('org_account');

        $organisation = $this->Api->post("/organisation", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));

        $this->set('organisation', $organisation);
    }

    

    public function change_password($organisation_id = null, $account_id = null, $check_hash = null) {
        
        // continue with normal html processing
        $orgAccount = null;
        
        if( $this->Session->check('org_account') ) {
            $orgAccount = $this->Session->read('org_account');
        }
        
        else if( $organisation_id && $account_id && $check_hash ) {
            $response = $this->Api->post('/organisation/account', array(
                'organisation_id' => $organisation_id,
                'account_id' => $account_id
            ));
            
            if( $response['status'] == 'failed' ) {
                $this->Session->setFlash('Password change operation cancelled. Invalid authentication information.');
                return $this->redirect('/organisation/login');
            }
            
            $orgAccount = $response['account'];
            
            $this->layout = 'web';
        }
        
        else {
            $this->Session->setFlash('Password change operation cancelled.');
            return $this->redirect('/organisation/login');
        }
        
        if ($this->request->is('ajax')) {

            $this->autoRender = false;

            $status = $this->Api->post("/organisation/account/change_password", array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'account_id' => $orgAccount['OrganisationAccount']['id'],
                'old_password' => $_POST['old_pass'],
                'new_password' => $_POST['new_pass']
            ));
            
            $this->Session->setFlash("Password change completed successfully. Please login again to continue.");

            return json_encode($status);
        }
        
        $this->set('orgAccount', $orgAccount);
    }
    
    public function groups(){
        $this->layout = 'admin';
        
        $org_account = $this->Session->read('org_account');
        
        $categories = $this->Api->post('/groups/', array(
            'organisation_id' => $org_account['Organisation']['id'],
            'subgroups' => true
        ));
        
        $this->set(compact('categories'));
    }

    /**
     * 
     */
    public function org_groups() {

        $this->layout = 'admin';

        $org_account = $this->Session->read('org_account');
        $post = $this->request->data;

        if (isset($post['action'])) {
            $this->autoRender = false;
            $result = array();

            switch ($post['action']) {
                case 'category':
                    $result = $this->Api->post('/groups/types/save', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'category_name' => $post['name'],
                        'category_id' => isset($post['id']) ? $post['id'] : null
                    ));
                    break;

                case 'group':
                    $result = $this->Api->post('/groups/group/save', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'group_name' => $post['name'],
                        'category_id' => $post['category_id'],
                        'group_id' => isset($post['id']) ? $post['id'] : null
                    ));
                    break;

                case 'date':
                    $result = $this->Api->post('/dates/update', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'date_name' => $post['name'],
                        'date_id' => $post['id']
                    ));
                    break;

                case 'remove_category':
                    $result = $this->Api->post('/groups/types/remove', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'category_id' => $post['category_id']
                    ));
                    break;

                case 'remove_group':
                    $result = $this->Api->post('/groups/group/remove', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'group_id' => $post['group_id']
                    ));
                    break;

                case 'remove_date':
                    $result = $this->Api->post('/dates/remove', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'date_id' => $post['date_id']
                    ));
                    break;
                
                case 'load_group_detail':
                    $result = $this->Api->post('/groups/group', array(
                        'organisation_id' => $org_account['Organisation']['id'],
                        'group_id' => $post['group_id']
                    ));
                    break;
            }

            echo json_encode($result);

            return;
        }

        if (isset($post['category_id'])) {
            $this->autoRender = false;

            $groups = $this->Api->post('/groups/group', array(
                'organisation_id' => $org_account['Organisation']['id'],
                'type_id' => $post['category_id']
            ));

            echo json_encode($groups);

            return;
        }

        $categories = $this->Api->post('/groups/', array(
            'organisation_id' => $org_account['Organisation']['id']
        ));

        $dates = $this->Api->post('/dates/', array(
            'organisation_id' => $org_account['Organisation']['id']
        ));

        $this->set(compact('categories', 'dates'));
    }

    public function members() {
        $this->layout = "admin";

        $orgAccount = $this->Session->read('org_account');
        
        $response = $this->Api->post('/batch', array(
            'categories' => array(
                'method' => 'post',
                'url' => '/organisation/categories',
                'params' => array('organisation_id' => $orgAccount['Organisation']['id'])
            ),
            'total_members' => array(
                'method' => 'post',
                'url' => '/organisation/getMembersTotal',
                'params' => array('organisation_id' => $orgAccount['Organisation']['id'])
            )
        ));

        $this->set('status', 'member');
        $this->set('total_members', $response['total_members']);
        $this->set('categories', $response['categories']);
    }

    public function visitors() {
        $this->layout = "admin";

        $orgAccount = $this->Session->read('org_account');

        $total_members = $this->Api->post("/organisation/getMembersTotal", array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'status' => 'visitor'
        ));

        $this->set("status", 'visitor');
        $this->set('total_members', $total_members);

        $this->render('members');
    }
    
    /**
     *  Allows public registration of members to an organisation category
     * 
     * @param mixed $category_slug
     */
    public function register() {
        $this->layout = "web";
        
        if( !isset($this->params['organisationSlug']) ) {
             $this->redirect("/");   
        }
        
        $org_slug = $this->params['organisationSlug'];
        
        if( !isset($this->request->query['category']) ) {
            $this->redirect("/");
        }
        
        $category_slug = $this->request->query['category'];
        
        $organisation = $this->Api->post('/organisation', array(
            'organisation_id' => $org_slug
        ));
        
        if( $organisation ) {
            $category = $this->Api->post('/organisation/category', array(
                'organisation_id' => $organisation['Organisation']['id'],
                'category_id' => $category_slug
            ));
            
            $this->set(compact('organisation', 'category'));
        }
        
        // if form is submited
        if( isset($_POST['first_name']) ) {
            $this->autoRender = false;
            
            $response = $this->Api->post('/organisation/registerMember', array(
                'organisation_id' => $organisation['Organisation']['id'],
                'category_id' => $category['OrganisationMemberCategory']['id'],
                'title' => $_POST['title'],
                'first_name' => $_POST['first_name'],
                'last_name' => $_POST['last_name'],
                'dob' => $_POST['dob'],
                'gender' => $_POST['gender'],
                'marital_status' => $_POST['marital_status'],
                'email' => $_POST['email'],
                'mobile_number' => $_POST['mobile_number'],
                'office_number' => $_POST['office_number'],
                'postal_address' => $_POST['postal_address']
            ));
            
            if( $response['status'] == 'success' ) {
                $this->redirect("/$org_slug/register_success?category=$category_slug" );
            }
            
            else {
                $this->Session->setFlash("Registration Failed");
            }
        }
    }
    
    public function register_success() {
        $this->layout = "web";
        
        if( !isset($this->request->query['category']) ) {
            $this->redirect("/");
        }
        
        $category_slug = $this->request->query['category'];
        $org_slug = $this->params['organisationSlug'];
        
        $organisation = $this->Api->post('/organisation', array(
            'organisation_id' => $org_slug
        ));
        
        if( $organisation ) {
            $category = $this->Api->post('/organisation/category', array(
                'organisation_id' => $organisation['Organisation']['id'],
                'category_id' => $category_slug
            ));
            
            $this->set(compact('organisation', 'category'));
        }
    }

    public function addMember() {

        $this->autoRender = false;

        if (isset($_POST['Member'])) {

            $result = $this->Api->post("/organisation/createMember", $_POST);

            echo json_encode($result);
        }
    }

    /**
     * action to flag a member as deleted
     */
    public function removeMember() {
        $this->autoRender = false;

        if (isset($_POST['member_ids'])) {
            $orgAccount = $this->Session->read('org_account');

            $result = $this->Api->post('/organisation/removeMember', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'member_ids' => $_POST['member_ids']
            ));

            echo json_encode($result);
        }
    }

    /**
     * returns the view for when a member is searched
     */
    public function find_member() {
        $this->layout = "ajax";

        $orgAccount = $this->Session->read('org_account');

        extract($_POST);

        $members = $this->Api->post('/organisation/find_member', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'term' => $text,
            'organisation_member_category_id' => $organisation_member_category_id
        ));

        $this->set('members', $members);
        $this->render('/Organisation/members_list');
    }

    /**
     * Triggers a member approval and returns the JSON response
     * 
     * @return json
     */
    public function approve() {
        $this->autoRender = false;

        $orgAccount = $this->Session->read('org_account');
        $memAccount = $this->Session->read('member_account');

        $result = $this->Api->post('/organisation/joinApproval', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'organisation_account_id' => $orgAccount['OrganisationAccount']['id'],
            'member_id' => $_POST['member_id'],
            'action' => $_POST['action']
        ));

        if ($result['status'] == "success") {
            $userName = $memAccount['Member']['first_name'] . ' ' . $memAccount['Member']['last_name'];
            
            switch( $result['member']['OrganisationMember']['source'] ) {
                case 'public':
                    $result['message'] = 'Join request approved by ' . $userName;
                    break;
                
                case 'registration':
                    $result['message'] = 'Registration approved by ' . $userName;
                    break;
            }
        }

        echo json_encode($result);
    }

    public function birthdays() {
        $this->autoLayout = false;
        
        $orgAccount = $this->Session->read('org_account');
        
        $result = $this->Api->post('/batch', array(
            'birthdays' => array(
                'method' => 'post',
                'url' => '/organisation/birthdays',
                'params' => array(
                    'organisation_id' => $orgAccount['Organisation']['id']
                )
            )
        ));
        
        if( $result['birthdays']['status'] == "success" ) {
            $this->set('members', $result['birthdays']['data']);
        }
    }
    
    public function images() {
        $org_id = $this->getOrgData('id');
        $this->set('org_id', $org_id);
        //$this->render('/members/table_view');
    }

    public function member_details($member_id) {
        //$this->autoLayout = false;

        $orgAccount = $this->Session->read('org_account');
        
        $org_id = $orgAccount['Organisation']['id'];
        
        $response = $this->Api->post('/batch', array(
            'member' => array(
                'url' => '/organisation/member',
                'method' => 'post',
                'params' => array(
                    'organisation_id' => $org_id,
                    'member_id' => $member_id
                )
            ),
            'org_info' => array(
                'url' => '/organisation',
                'method' => 'post',
                'params' => array(
                    'organisation_id' => $org_id
                )
            )
        ));
        
        extract($response);
        
        $cat_res = $this->Api->post('/organisation/memberCategory', array(
            'organisation_id' => $org_id,
            'category_id' => $member['OrganisationMember']['organisation_member_category_id']
        ));
        
        $category = $cat_res['data'];

        $this->set(compact('member', 'org_info', 'org_id', 'category'));
    }

    /**
     * Returns the view for the member profile
     * 
     * @param type $member_id
     */
    public function member_profile($category_id, $member_id = null) {
        $this->layout = "ajax";

        $orgAccount = $this->Session->read('org_account');
        $nextID = '';

        if ($member_id != null && intval($member_id) > 0) {

            $member = $this->Api->post("/organisation/member", array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'member_id' => $member_id
            ));

            $this->set('member', $member);
        } 
        
        $org_info = $this->Api->post('/organisation', array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        $category = $this->Api->post('/organisation/memberCategory', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'category_id' => $category_id
        ));

        $nextID = $category['data']['category']['id_prefix'] . $category['data']['category']['id_next_increment'];

        $this->set(compact('org_info', 'nextID'));
        $this->set('category', $category['data']);
    }

    /**
     * gets the data for the table view
     */
    public function members_list($organisation_member_category_id, $sort_order = 'alpha') {
        
        $this->autoLayout = false;
        
        $orgAccount = $this->Session->read('org_account');
        
        $offset = isset($_POST['offset']) ? $_POST['offset'] : 0;
        $limit = isset($_POST['limit']) ? $_POST['limit'] : 30;
        $text = isset($_POST['text']) ? $_POST['text'] : null;

        $members = $this->Api->post('/organisation/find_member', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'sort_order' => $sort_order,
            'term' => $text,
            'organisation_member_category_id' => $organisation_member_category_id,
            'offset' => $offset,
            'limit' => $limit
        ));

        $this->set('members', $members);
    }
    
    public function member_autocomplete_list() {
        $this->autoRender = false;
        
        if( isset($_GET['term']) ) {
            $term = $_GET['term'];
            $orgAccount = $this->Session->read('org_account');
            
            $results = $this->Api->post('/organisation/members/list', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'term' => $term,
                'limit' => 5
            ));
            
            return json_encode($results);
        }
    }
    
    /**
     * Change member status between "member", "visitor", "deceased"
     * @param type $status
     */
    public function change_status($status) {
        $this->autoRender = false;
        
        if( $status && isset($_POST['member_ids']) ) {
            $orgAccount = $this->Session->read('org_account');
            
            $response = $this->Api->post('/organisation/changeStatus', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'member_id' => $_POST['member_ids'],
                'status' => $status
            ));
            
            echo json_encode($response);
        }
    }
    
    public function change_category() {
        $this->layout = "ajax";
        
        $orgAccount = $this->Session->read('org_account');
        
        if( $this->request->is("post") && isset($this->request->data['member_ids']) ) {
            
            $this->autoRender = false;
            
            $member_ids = $this->request->data['member_ids'];
            $category_id = $this->request->data['category_id'];
            
            $response = $this->Api->post('/organisation/category/change', array(
                'organisation_id' => $orgAccount['Organisation']['id'],
                'category_id' => $category_id,
                'member_id' => $member_ids
            ));
            
            return json_encode($response);
        }
        
        
        $categories = $this->Api->post("/organisation/categories", array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        $this->set(compact('categories'));
    }

    public function remove_child() {
        $this->autoRender = false;

        if (isset($_POST['child_id'])) {
            $org_account = $this->Session->read('org_account');

            $response = $this->Api->post('/members/removeChild', array(
                'organisation_id' => $org_account['Organisation']['id'],
                'member_id' => $_POST['member_id'],
                'child_id' => $_POST['child_id']
            ));

            return json_encode($response);
        }
    }
    
    /**
     * Runs the account activation process
     * 
     * @param type $organisation_id
     * @param type $username
     * @param type $check_hash
     */
    public function account_activate($organisation_id, $username, $check_hash) {
        $this->autoRender = false;
        
        $response = $this->Api->post('/organisation/account/activate', array(
            'organisation_id' => $organisation_id,
            'account_username' => $username,
            'validation_hash' => $check_hash
        ));
        
        if( $response['status'] == 'success' ) {
            $this->Session->write('member_account', $response['member_account']);
            
            if( $response['member_account']['MemberAccount']['reset_requested'] ) {
                $this->Session->setFlash("Account successfully activated. Password change required.");
                $this->redirect('/member/change_password');
            }
            
            else {
                $this->Session->write('org_account', $response['org_account']);
                $this->Session->setFlash("Account successfully activated. Welcome.");
            }
            
            // we'll only get here if not redirected before.
            $this->redirect('/' . $response['org_account']['Organisation']['slug']);
        }
        
        else {
            $this->Session->setFlash("Account activation failed. Please try again or contact support");
            
            $this->redirect(array('action' => 'login'));
        }
    }

    public function removePhoneNumber() {
        $this->autoRender = false;
        
        if( $this->request->is('post') && isset($this->request->data['id']) ) {
            $response = $this->Api->post('/members/remove_phone_number', array(
                'member_phone_number_id' => $this->request->data['id'],
                'member_id' => $this->request->data['member_id']
            ));
            
            return json_encode($response);
        }
    }
    
    public function removeEmail() {
        $this->autoRender = false;
        
        if( $this->request->is('post') && isset($this->request->data['id']) ) {
            $response = $this->Api->post('/members/remove_email', array(
                'member_email_id' => $this->request->data['id'],
                'member_id' => $this->request->data['member_id']
            ));
            
            return json_encode($response);
        }
    }
    
    public function remove() {
        $this->autoRender = false;
        
        if( $this->request->is('ajax') && $this->request->is('post') ) {
            $member_account = $this->Session->read('member_account');
            
            if( !$member_account ) {
                return json_encode(array('status' => 'failed', 'message' => 'You must be logged in to perform this action'));
            }
            
            $data = $this->request->data;
            
            $response = $this->Api->post('/organisation/remove', array(
                'organisation_id' => $data['organisation_id'],
                'member_account_id' => $member_account['MemberAccount']['id']
            ));
            
            return json_encode($response);
        }
    }
    
    public function notifications($action = null, $notification_type_id = null, $notification_id = null, $read = 1) {
        
        $orgAccount = $this->Session->read('org_account');
        
        if( $action != null ) {
            $this->autoRender = false;
            
            $response = null;
            
            switch($action) {
                case 'mark_read':
                    $response = $this->Api->post('/organisation/notifications/mark_read', array(
                        'organisation_id' => $orgAccount['Organisation']['id'],
                        'notification_type_id' => $notification_type_id,
                        'notification_id' => $notification_id,
                        'read' => $this->request->query['read']
                    ));
                    break;
                
                case 'mark_all_read':
                    $response = $this->Api->post('/organisation/notifications/mark_all_read', array(
                        'organisation_id' => $orgAccount['Organisation']['id'],
                        'read' => 1
                    ));
                    break;
                
                case 'latest':
                    $notifications = $this->Api->post('/organisation/notifications', array(
                        'organisation_id' => $orgAccount['Organisation']['id'],
                        'limit' => 10,
                        'offset' => 0
                    ));
                    
                    $this->autoRender = true;
                    $this->set('notifications', $notifications['list']);
                    $this->render('/Elements/organisation/notifications');
                    break;
            }
            
            if( $response ) {
                return json_encode($response);
            }
        }
        
        $notifications = $this->Api->post('/organisation/notifications', array(
            'organisation_id' => $orgAccount['Organisation']['id'],
            'limit' => 50,
            'offset' => 0
        ));
        
        if( $notifications['status'] == 'success' ) {
            $this->set('notifications', $notifications['list']);
        }
        
        else {
            $this->set('notifications', array());
        }
    }
    
    public function approvals() {
        $this->layout = "admin";
        
        $orgAccount = $this->Session->read('org_account');
        
        $feed = $this->Api->post('/organisation/activityFeed', array(
            'organisation_id' => $orgAccount['Organisation']['id']
        ));
        
        $this->set(compact('feed'));
    }
}
